package com.zyh.day05.function

import org.apache.spark.sql.{DataFrame, SparkSession}

object UserDefineFunctionTest {
  def main(args: Array[String]): Unit = {
    val spark: SparkSession = SparkSession.builder()
      .master("local[*]")
      .appName("udf")
      .getOrCreate()
    val list = List((1, "xiao1hei", "F"), (2, "xiao2hei", "M"))
    import spark.implicits._
    val df: DataFrame = list.toDF("id", "name", "sex")

    //匿名函数 F=>女 M=>男 else=>其他
    val converSex = (s:String)=>
      s match{
        case "F"=>"女"
        case "M"=>"男"
        case _=>"其他"
      }
    //注册函数
    spark.udf.register("conver_sex",converSex)

    df.createOrReplaceTempView("t_user")

    val result: DataFrame = spark.sql("select id,name,sex,conver_sex(sex) from t_user")
    result.show()
    spark.close()
  }
}
